/* eslint-disable no-nested-ternary */
import React from 'react';
import { TreeSelect, Select, DatePicker, message } from 'antd';
import moment from 'moment';
import cn from 'classnames';
import styles from './index.less';
import { TaskPriorityList, TaskStatus } from '../../utils';

const { Option } = Select;

const getItem = val => {
    if (val === undefined || val === '') {
        return null;
    }
    let temp = val;
    if (typeof val === 'string') {
        temp = Number(val);
    }
    const arr = TaskPriorityList.filter(item => item.value === temp);
    if (arr && arr.length > 0) {
        return arr[0];
    }
    return null;
};

const getEmploy = (val, list = []) => {
    const arr = list.filter(item => item.value === val);
    if (arr && arr.length > 0) {
        return arr[0];
    }
    return null;
};

const getEmployeeCode = () => {
    const user = localStorage.getItem('user');
    if (user) {
        const { employeeCode = '' } = JSON.parse(user);
        return employeeCode;
    }
    return '';
};

const QuickTaskBar = ({
    size = 'normal',
    employeeList = [],
    isCheck = false,
    executeEmployeeCode,
    planStartTime,
    planEndTime,
    taskPriority,
    auditEmployeeCode,
    acceptanceEmployeeCode,
    onChange,
    taskType,
    // parentEndTime,
    cycleTaskFlag,
    acceptanceStatus,
    auditStatus,
    taskStatus
}) => {
    // console.log(executeEmployeeCode);
    // console.log(planStartTime);
    // console.log(planEndTime);
    // console.log(taskPriority);
    // console.log(auditEmployeeCode);
    // console.log(acceptanceEmployeeCode);
    // console.log('cycleTaskFlag', cycleTaskFlag);
    const [taskExecutor, setTaskExecutor] = React.useState(getEmploy(executeEmployeeCode, employeeList));
    const [taskChecker, setTaskChecker] = React.useState(getEmploy(auditEmployeeCode, employeeList));
    const [taskAccepter, setTaskAccepter] = React.useState(getEmploy(acceptanceEmployeeCode, employeeList));
    const [startMode, setStartMode] = React.useState(
        planStartTime && planStartTime.indexOf('00:00:00') === -1 ? 'time' : 'date'
    );
    const [endMode, setEndMode] = React.useState(
        planEndTime && planEndTime.indexOf('23:59:59') === -1 ? 'time' : 'date'
    );
    const [startDate, setStartDate] = React.useState(planStartTime || '');
    const [endDate, setEndDate] = React.useState(planEndTime || '');
    const [taskLevel, setTaskLevel] = React.useState(getItem(taskPriority) || getItem(1));
    const [employeeCode] = React.useState(getEmployeeCode());

    const isFirst = React.useRef(false);
    const handleTime = (value, type) => {
        if (type === 'start') {
            if (!endDate || (endDate && value.isBefore(endDate))) {
                setStartDate(value.format(startMode === 'date' ? 'YYYY-MM-DD 00:00:00' : 'YYYY-MM-DD HH:mm:ss'));
            } else {
                message.error('不可大于截止时间');
            }
        } else if (type === 'end') {
            // if (parentEndTime && value.isAfter(parentEndTime)) {
            //     const str = moment(parentEndTime).format(
            //         parentEndTime.indexOf('23:59:59') !== -1 ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm'
            //     );
            //     message.error(`不可大于上级任务截止时间${str}`);
            //     return;
            // }
            if (!startDate || (startDate && value.isAfter(startDate))) {
                setEndDate(value.format(endMode === 'date' ? 'YYYY-MM-DD 23:59:59' : 'YYYY-MM-DD HH:mm:ss'));
            } else {
                message.error('不可小于开始时间');
            }
        }
    };

    const handleTimeChange = (date, dateString, type) => {
        // console.log('handleTimeChange -> dateString', dateString);
        if (!dateString) {
            if (type === 'start') {
                setStartDate(null);
            } else {
                setEndDate(null);
            }
        } else {
            handleTime(date, type);
        }
    };

    const handleTimePanel = (value, mode, type) => {
        if (type === 'start') {
            setStartMode(mode);
        } else {
            setEndMode(mode);
            setEndDate(value.format(mode === 'date' ? 'YYYY-MM-DD 23:59:59' : 'YYYY-MM-DD HH:mm:ss'));
        }
    };

    const handleSelect = val => {
        setTaskLevel(getItem(val));
    };

    const handleTreeSelect = (val, type) => {
        // console.log('handleTreeSelect -> val', val);
        if (type === 'accepter') {
            if (taskExecutor && val === taskExecutor.value) {
                message.error('不可与执行人重复');
            } else {
                setTaskAccepter(getEmploy(val, employeeList));
            }
            return;
        }
        if (type === 'checker') {
            if (val === employeeCode) {
                message.error('不可选自己');
            } else if (taskExecutor && val === taskExecutor.value) {
                message.error('不可与执行人重复');
            } else {
                setTaskChecker(getEmploy(val, employeeList));
            }
            return;
        }
        if (taskChecker && val === taskChecker.value) {
            message.error('不可与审核人重复');
        } else if (taskAccepter && val === taskAccepter.value) {
            message.error('不可与验收人重复');
        } else {
            setTaskExecutor(getEmploy(val, employeeList));
        }
    };

    const getTitle = title => {
        if (size === 'mini') {
            return '';
        }
        return title;
    };

    React.useEffect(() => {
        if (isFirst.current) {
            if (onChange) {
                onChange({
                    executeEmployeeCode: taskExecutor ? taskExecutor.value : '',
                    planStartTime: startDate,
                    planEndTime: endDate,
                    taskPriority: taskLevel ? taskLevel.value : '',
                    auditEmployeeCode: taskChecker ? taskChecker.value : '',
                    acceptanceEmployeeCode: taskAccepter ? taskAccepter.value : ''
                });
            }
        } else {
            isFirst.current = true;
        }
    }, [startDate, endDate, taskLevel, taskExecutor, taskChecker, taskAccepter]);

    React.useEffect(() => {
        if (executeEmployeeCode) {
            setTaskExecutor(getEmploy(executeEmployeeCode, employeeList));
        } else {
            setTaskExecutor(getEmploy(employeeCode, employeeList));
        }
        setTaskChecker(getEmploy(auditEmployeeCode, employeeList));
        setTaskAccepter(getEmploy(acceptanceEmployeeCode, employeeList));
    }, [employeeList]);

    React.useEffect(() => {
        setTaskExecutor(getEmploy(executeEmployeeCode || employeeCode, employeeList));
        setTaskChecker(getEmploy(auditEmployeeCode, employeeList));
        setTaskAccepter(getEmploy(acceptanceEmployeeCode, employeeList));
        setStartMode(planStartTime && planStartTime.indexOf('00:00:00') === -1 ? 'time' : 'date');
        setEndMode(planEndTime && planEndTime.indexOf('23:59:59') === -1 ? 'time' : 'date');
        setStartDate(planStartTime || '');
        setEndDate(planEndTime || '');
        setTaskLevel(getItem(taskPriority) || getItem(1));
    }, [executeEmployeeCode, planStartTime, planEndTime, taskPriority, auditEmployeeCode, acceptanceEmployeeCode]);

    return (
        <div className={cn(styles.quickTask, { [styles.mini]: size === 'mini' })}>
            <div
                key="1"
                className={cn({
                    [styles.isCheck]: isCheck && !taskExecutor,
                    [styles.isActive]: taskExecutor && !(taskType === 'change_task' && taskStatus !== TaskStatus.READY)
                })}
                title={
                    taskType === 'change_task' && taskStatus !== TaskStatus.READY ? '任务已开始，不可变更' : '执行人'
                }
            >
                {!(size === 'mini' && taskExecutor) && (
                    <i className="icon iconfont iconuser">
                        <span>*</span>
                    </i>
                )}
                {size === 'mini' && taskExecutor ? (
                    <div className={styles.selectedTitle}>{taskExecutor ? taskExecutor.title : getTitle('执行人')}</div>
                ) : taskExecutor ? (
                    taskExecutor.title
                ) : (
                    getTitle('执行人')
                )}
                {!(taskType === 'change_task' && taskStatus !== TaskStatus.READY) && (
                    <TreeSelect
                        showSearch
                        className={styles.treeSelect}
                        dropdownClassName={styles.treeSelectDropDown}
                        dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                        treeDefaultExpandAll
                        treeNodeFilterProp="title"
                        value={taskExecutor ? taskExecutor.value : ''}
                        treeData={employeeList}
                        onChange={handleTreeSelect}
                    ></TreeSelect>
                )}
            </div>
            <div
                key="2"
                className={cn({
                    [styles.isActive]: startDate && !(taskType === 'change_task' && taskStatus !== TaskStatus.READY)
                })}
                title={
                    taskType === 'change_task' && taskStatus !== TaskStatus.READY ? '任务已开始，不可变更' : '开始时间'
                }
            >
                {!(size === 'mini' && startDate) && <i className="icon iconfont iconkaishishijian"></i>}
                {size === 'mini' && startDate ? (
                    <div className={styles.selectedTitle}>
                        {startDate
                            ? moment(startDate).format(startMode === 'date' ? 'MM-DD' : 'MM-DD HH:mm')
                            : getTitle('开始时间')}
                    </div>
                ) : startDate ? (
                    moment(startDate).format(startMode === 'date' ? 'MM-DD' : 'MM-DD HH:mm')
                ) : (
                    getTitle('开始时间')
                )}
                {!(taskType === 'change_task' && taskStatus !== TaskStatus.READY) && (
                    <DatePicker
                        showTime
                        className={styles.datePick}
                        value={startDate ? moment(startDate) : moment()}
                        // defaultValue={startDate ? moment(startDate) : ''}
                        dropdownClassName={styles.dropdownDatePick}
                        style={{ width: 50, position: 'absolute', left: 0 }}
                        format={startMode === 'date' ? 'MM-DD' : 'MM-DD HH:mm'}
                        onOk={e => handleTime(e, 'start')}
                        onChange={(e1, e2) => handleTimeChange(e1, e2, 'start')}
                        onPanelChange={(e1, e2) => handleTimePanel(e1, e2, 'start')}
                    />
                )}
            </div>
            <div
                key="3"
                // className={cn({
                //     [styles.isCheck]:
                //         isCheck && (!endDate || (endDate && parentEndTime && moment(endDate).isAfter(parentEndTime))),
                //     [styles.isActive]: endDate
                // })}
                className={cn({
                    [styles.isCheck]: isCheck && !endDate,
                    [styles.isActive]: endDate
                })}
                title="截止时间"
            >
                {!(size === 'mini' && endDate) && (
                    <i className="icon iconfont iconjiezhishijian-1">
                        <span>*</span>
                    </i>
                )}
                {size === 'mini' && endDate ? (
                    <div className={styles.selectedTitle}>
                        {endDate
                            ? moment(endDate).format(endMode === 'date' ? 'MM-DD' : 'MM-DD HH:mm')
                            : getTitle('截止时间')}
                    </div>
                ) : endDate ? (
                    moment(endDate).format(endMode === 'date' ? 'MM-DD' : 'MM-DD HH:mm')
                ) : (
                    getTitle('截止时间')
                )}
                <DatePicker
                    showTime
                    allowClear={false}
                    className={styles.datePick}
                    value={endDate ? moment(endDate) : moment()}
                    dropdownClassName={styles.dropdownDatePick}
                    format={endMode === 'date' ? 'MM-DD' : 'MM-DD HH:mm'}
                    onOk={e => handleTime(e, 'end')}
                    onChange={(e1, e2) => handleTimeChange(e1, e2, 'end')}
                    onPanelChange={(e1, e2) => handleTimePanel(e1, e2, 'end')}
                />
            </div>
            <div
                key="4"
                className={cn({ [styles.isCheck]: isCheck && !taskLevel, [styles.isActive]: taskLevel })}
                title="优先级"
            >
                {!(size === 'mini' && taskLevel) && (
                    <i className="icon iconfont iconyouxianji1">
                        <span>*</span>
                    </i>
                )}
                {size === 'mini' && taskLevel ? (
                    <div className={styles.selectedTitle}>{taskLevel ? taskLevel.text : getTitle('优先级')}</div>
                ) : taskLevel ? (
                    taskLevel.text
                ) : (
                    getTitle('优先级')
                )}
                <Select
                    className={styles.taskSelect}
                    value={taskLevel ? taskLevel.value : 1}
                    dropdownMatchSelectWidth={false}
                    onSelect={handleSelect}
                >
                    {TaskPriorityList.map(item => (
                        <Option value={item.value} key={item.value}>
                            {item.text}
                        </Option>
                    ))}
                </Select>
            </div>
            {!(taskType === 'change_task' && cycleTaskFlag) && (
                <div
                    key="5"
                    className={cn({
                        [styles.isActive]: taskChecker && !(taskType === 'change_task' && auditStatus === 3)
                    })}
                    title={taskType === 'change_task' && auditStatus === 3 ? '任务待审核中，暂不可变更' : '审核人'}
                >
                    {!(size === 'mini' && taskChecker) && <i className="icon iconfont iconshenheren1"></i>}
                    {size === 'mini' && taskChecker ? (
                        <div className={styles.selectedTitle}>
                            {taskChecker ? taskChecker.title : getTitle('审核人')}
                        </div>
                    ) : taskChecker ? (
                        taskChecker.title
                    ) : (
                        getTitle('审核人')
                    )}
                    {!(taskType === 'change_task' && auditStatus === 3) && (
                        <TreeSelect
                            showSearch
                            className={styles.treeSelect}
                            dropdownClassName={styles.treeSelectDropDown}
                            dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                            treeDefaultExpandAll
                            allowClear
                            treeNodeFilterProp="title"
                            value={taskChecker ? taskChecker.value : ''}
                            treeData={employeeList}
                            onChange={e => handleTreeSelect(e, 'checker')}
                        ></TreeSelect>
                    )}
                </div>
            )}
            {!(taskType === 'change_task' && cycleTaskFlag) && (
                <div
                    key="6"
                    className={cn({
                        [styles.isActive]: taskAccepter && !(taskType === 'change_task' && acceptanceStatus === 3)
                    })}
                    title={taskType === 'change_task' && acceptanceStatus === 3 ? '任务待验收中，暂不可变更' : '验收人'}
                >
                    {!(size === 'mini' && taskAccepter) && <i className="icon iconfont iconyanshouren1" />}
                    {size === 'mini' && taskAccepter ? (
                        <div className={styles.selectedTitle}>
                            {taskAccepter ? taskAccepter.title : getTitle('验收人')}
                        </div>
                    ) : taskAccepter ? (
                        taskAccepter.title
                    ) : (
                        getTitle('验收人')
                    )}
                    {!(taskType === 'change_task' && acceptanceStatus === 3) && (
                        <TreeSelect
                            showSearch
                            className={styles.treeSelect}
                            dropdownClassName={styles.treeSelectDropDown}
                            dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                            treeDefaultExpandAll
                            allowClear
                            treeNodeFilterProp="title"
                            value={taskAccepter ? taskAccepter.value : ''}
                            treeData={employeeList}
                            onChange={e => handleTreeSelect(e, 'accepter')}
                        ></TreeSelect>
                    )}
                </div>
            )}
        </div>
    );
};

export default QuickTaskBar;
